<template>
  <div>
<!--    引入批量删除的按钮-->
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
<el-tree :data="data"
         :props="defaultProps"
         ref="categoryTree"
           show-checkbox
           :default-expanded-keys="expandedKey"
           node-key="id"
           :expand-on-click-node="false">
           <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)">
            Append
          </el-button>
<!--          增加edit按钮修改信息-->
           <el-button
             type="text"
             size="mini"
             @click="() => edit(data)">
            Edit
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)">
            Delete
          </el-button>
        </span>
      </span>
</el-tree>
<!--    引入了对话框  -->
<!--    1. visible.sync="dialogVisible" 动态绑定 dialogVisible
        如果 dialogVisible 为 true就显示对话框,否则不显示
        2. :model="category" 动态绑定category数据对象
-->
  <el-dialog title="添加/修改分类" :visible.sync="dialogVisible" width="20%">
    <el-form :model="category">
      <el-form-item label="分类名" >
        <el-input v-model="category.name" autocomplete="off"></el-input>
      </el-form-item>
 <!-- 增加修改所需要的字段 ，这里也会同步影响到添加的对话框 -->
      <el-form-item label="图标" >
        <el-input v-model="category.icon" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="单位" >
        <el-input v-model="category.proUnit" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addOrUpdate">确 定</el-button>
    </div>
  </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      data: [],
      dialogType: "", //标识对话框的类型
      category: {//初始化添加的分类的表单对象数据, 注意category的属性名和CategoryEntity属性/字段 对应
        id: null,
        name: "",
        parentId: 0,
        catLevel: 0,
        isShow: 1,
        sort: 0,
        icon: "",
        proUnit: "",
        proCount: 0
      },
      dialogVisible: false, //控制是否显示对话框
      expandedKey:[],
      defaultProps: {
        children: 'childrenCategories',
        label: 'name'
      }
    }
  },
  methods: {
    //处理批量删除
    batchDelete() {

      //通过ref可以获取勾选的分类信息
      var checkedNodes = this.$refs.categoryTree.getCheckedNodes()
      //收集选中的分类的ids和分类名
      var ids = []
      var categoryNames = []
      for (var i = 0;i<checkedNodes.length; i++){
        ids.push(checkedNodes[i].id)
        categoryNames.push(checkedNodes[i].name)
      }

      //给出提示,等用户确定后调用后端程序接口,实现逻辑删除
      this.$confirm(`是否批量删除【${categoryNames}】菜单?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() =>{
        // 2.如果点击确认,发出请求,完成批量删除
        this.$http({
          // url: this.$http.adornUrl('/commodity/category/list'),
          url: 'http://localhost:9090/commodity/category/delete',
          method: 'post',
          data: this.$http.adornData(ids, false)  // 发出请求时，携带的数据
        }).then(({data}) => { // {data}解构了返回数据的data部分
          this.$message({
            message: '批量删除成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.getDataList()
            }
          })
          // 刷新分类列表
          this.getCategories()
        })
      }).catch(() => { // 3.如果点击取消则不删除
      })

    },
    //增加方法,处理添加/修改分类
    addOrUpdate() {
      if ("add" == this.dialogType) {
        this.addCategory()
      }
      if ("edit" == this.dialogType) {
        this.updateCategory()
      }
    },

    //真正修改分类信息(调用后端程序的接口)
    updateCategory(){

      //1.注意分析:这里我们只是提交需要修改的字段信息,没有提交的字段,在数据库中不被修改
      var {id, name, icon, proUnit} = this.category

      this.$http({
        // url: this.$http.adornUrl('/commodity/category/list'),
        url: 'http://localhost:9090/commodity/category/update',
        method: 'post',
        data: this.$http.adornData({id, name, icon, proUnit}, false)  // 发出请求时，携带的数据
      }).then(({data}) => {
        this.$message({
          message: '分类信息修改成功',
          type: 'success',
        })
        //关闭添加分类的对话框
        this.dialogVisible = false
        // 刷新分类列表
        this.getCategories()
        //设置需要展开的菜单
        this.expandedKey = [this.category.parentId]
      })
    },

    //点击edit按钮,回显分类信息
    edit(data) {
      console.log("data=>", data)

      //显示回显对话框-准备修改
      this.dialogType = "edit"
      this.dialogVisible = true

      //发出请求到后端请求数据库获取该分类信息[实时数据]
      this.$http({
        // url: this.$http.adornUrl('/commodity/category/list'),
        // 飘号` `包起来前端才会解析${data.id}
        url: `http://localhost:9090/commodity/category/info/${data.id}`,
        method: 'post',
       //不用携带数据了,id自己获取了
      }).then(({data}) => {
         // console.log("data => ",data)
         //将返回的data信息绑定到category对象
        this.category.name = data.category.name
        this.category.icon = data.category.icon
        this.category.proUnit = data.category.proUnit
        this.category.id = data.category.id
        this.category.parentId = data.category.parentId
        //不修改的暂不绑定
      })

    },
    //处理点击添加分类，真正调用后端接口，将分类信息入库
    addCategory() {
      // 2.如果点击确认,发出请求,完成删除
      this.$http({
        // url: this.$http.adornUrl('/commodity/category/list'),
        url: 'http://localhost:9090/commodity/category/save',
        method: 'post',
        data: this.$http.adornData(this.category, false)  // 发出请求时，携带的数据
      }).then(({data}) => {
        this.$message({
          message: '分类信息保存成功',
          type: 'success',
        })
        //关闭添加分类的对话框
        this.dialogVisible = false
        // 刷新分类列表
        this.getCategories()
        //设置需要展开的菜单
        this.expandedKey = [this.category.parentId]
      })
    },
    append (data) { // 处理点击添加分类 - 显示添加分类的对话框
      console.log('data=>', data)
      //显示添加分类的对话框
      //设置对话框的类型
      this.dialogType = "add"
      this.dialogVisible = true

      this.category.parentId = data.id
      this.category.sort = 0
      this.category.proUnit = ""
      this.category.proCount = 0
      this.category.name = ""
      this.category.isShow = 1
      this.category.id = null
      this.category.icon = ""
      //添加按钮对应的data所属其父类层级,新加的分类为子类 ,这里 *1 将字符串转为数值再 + 1
      this.category.catLevel = data.catLevel * 1 + 1
    },
    remove (node, data) { // 处理点击删除分类
      console.log('data', data)
      console.log('node', node)
      // 1.获取删除分类的id
      var ids = [data.id]

      this.$confirm(`是否删除【${data.name}】菜单?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() =>{
         // 2.如果点击确认,发出请求,完成删除
        this.$http({
          // url: this.$http.adornUrl('/commodity/category/list'),
          url: 'http://localhost:9090/commodity/category/delete',
          method: 'post',
          data: this.$http.adornData(ids, false)  // 发出请求时，携带的数据
        }).then(({data}) => { // {data}解构了返回数据的data部分
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.getDataList()
            }
          })
              // 刷新分类列表
              this.getCategories()
              //设置需要展开的菜单
              this.expandedKey = [node.parent.data.id]
            })
        }).catch(() => { // 3.如果点击取消则不删除
      })
    },

    // 获取数据列表,带层级
    getCategories () {
      this.$http({
        // url: this.$http.adornUrl('/commodity/category/list'),
        // url: 'http://localhost:9090/commodity/category/list',
        // url就是 http://localhost:5050/api + /commodity/category/list
        url: this.$http.adornUrl('/commodity/category/list'),
        method: 'get'
      }).then(({data}) => { // {data}解构了返回数据的data部分
        console.log('拿到的数据', data)
        this.data = data.data
      })
    }
  },
  created () {
    this.getCategories()
  }
}
</script>
